/**
 * Created by dmrj on 2016/5/14.
 */
define(['jquery', 'appConst', 'business/group/groupConfig', 'model/global', 'stringUtils', 'model/group', 'appMessageBox', 'jquery-form/jquery-form.min', 'domReady!'], function ($, appConst, groupConfig, global, stringUtils, groupM, msgBox) {

    var that;
    var components = {};
    var data = {
        searchProject: {},
        searchUser: {},
        projectResult: {},
        userResult: {},
        projectDS: [],
        userDS: []
    };
    return {

        init: function () {
            that = this;
            components = {
                "form_group": $("#group-form"),
                "input_id": $("#g_id"),
                "input_gdetail_name": $("#input_gdetail_name"),
                "input_psearch": $("#search-input-addProject"),
                "btn_passign": $("#btn-search-addProject"),
                "input_pfilter": $("#search-input-filterProject"),
                "btn_pfilter": $("#btn-simple-filterProject"),
                "input_usearch": $("#search-input-addUser"),
                "btn_uassign": $("#btn-search-addUser"),
                "input_ufilter": $("#search-input-fiterUser"),
                "btn_ufilter": $("#btn-simple-fiterUser"),
                "tbl_project": $("#tbl_project"),
                "tbl_user": $("#tbl_user"),
                "div_pnumber": $("#div_pnumber"),
                "div_unumber": $("#div_unumber")
            };

            data.searchProject = {"search_EQ_groupId": components.input_id.val()};
            data.searchUser = {"search_EQ_groupId": components.input_id.val()};

            that.formSubmit();
            that.initTable();
            that.initProjectsNotInThisGroup();
            that.reloadProjectsNotInThisGroup();
            that.initUsersNotInThisGroup();
            that.reloadUsersNotInThisGroup();
            that.initAddClickEvent();
            that.initFilterClickEvent();
        },

        formSubmit: function () {
            $(components.form_group).validate({
                rules: {
                    name: {
                        required: true,
                        keyContainBlankCheck: true,
                        remote: {
                            type: "POST",
                            url: "group/checkGroupName",
                            dataType: 'json',
                            data: {
                                groupName: function () {
                                    return components.input_gdetail_name.val().trim();
                                },
                                groupId: function () {
                                    return components.input_id.val();
                                }
                            }
                        }
                    }
                },
                messages: {
                    name: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('GROUP_NAME')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('GROUP_NAME'))
                    }
                },
                submitHandler: function (form) {
                    $(form).ajaxSubmit({
                        success: function (d) {
                            if (d.code == 0) {

                                msgBox.errorBox(d.message, "MENU_SYSTEM_GROUP");
                                return false;
                            }
                            if (d.code == 1) {

                                msgBox.successBox({
                                    title: $.i18n.prop("MESSAGEBOX_TITLE_TIPS"),
                                    content: $.i18n.prop("PROJECT_SAVE_SUCCESS")
                                });
                            }

                            $("#group-form").addClass('submited');
                        },
                        error: function (e) {
                            if (e.status == 401) {
                                msgBox.sessionFailureBox();
                            }
                            if (e.status == 500) {
                                msgBox.serverFailureBox();
                            }
                            if (e.status == 404) {
                                msgBox.pathFailureBox();
                            }
                        }
                    });
                },
                errorPlacement: function (error, element) {
                    error.insertAfter(element.parent());
                }
            });
        },

        initTable: function () {
            var customProjectParams = function (params) {
                $.extend(params, data.searchProject);
                params['draw'] = params.draw;
                return params;
            };

            var customUserParams = function (params) {
                $.extend(params, data.searchUser);
                params['draw'] = params.draw;
                return params;
            };

            components.tbl_project.DataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": false,
                "ordering": false,
                "ajax": {
                    "url": 'group/findProjectsForGroupByName',
                    "type": "POST",
                    "dataSrc": function (d) {
                        components.div_pnumber.text(d.recordsTotal);
                        return d.body;
                    },
                    "data": customProjectParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "id"},
                    {"data": "name"},
                    {"data": null}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [3],
                        "render": function (data, type, full) {
                            var str = '<button type="button" class="btn btn-xs btn-danger pdetails-control" id="' + full.id + '"><i class="fa fa-minus"></i></button>';
                            return str;
                        }
                    }
                ]
            });
            components.tbl_user.DataTable({
                "sDom": "t<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "pageLength": global.getPageSize(),
                "processing": true,
                "paging": true,
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": false,
                "ordering": false,
                "ajax": {
                    "url": 'group/findUsersForGroupByName',
                    "type": "POST",
                    "dataSrc": function (d) {
                        components.div_unumber.text(d.recordsTotal);
                        return d.body;
                    },
                    "data": customUserParams,
                    "traditional": true,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "id"},
                    {"data": "loginName"},
                    {"data": "name"},
                    {"data": null}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var str = '<button type="button" class="btn btn-xs btn-danger udetails-control" id="' + full.id + '"><i class="fa fa-minus"></i></button>';
                            return str;
                        }
                    }
                ]
            });

            that.drawNumber(components.tbl_project);
            that.drawNumber(components.tbl_user);
            that.initGroupDetailEvent();
        },

        drawNumber: function (table) {
            table.DataTable().on('draw.dt', function () {
                var dt = $(this).dataTable();
                dt.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                    var pageNum = dt.api().page();
                    var pageSize = dt.api().page.len();
                    cell.innerHTML = pageNum * pageSize + i + 1;
                });
            });
        },

        initGroupDetailEvent: function () {
            components.tbl_project.on('click', 'button.pdetails-control', function () {
                //components.input_pfilter.val('');
                that.deleteForGroups("group/deleteProject", null, $(this).attr("id"), components.tbl_project);
            });

            components.tbl_user.on('click', 'button.udetails-control', function () {
                //components.input_ufilter.val('');
                that.deleteForGroups("group/deleteUser", $(this).attr("id"), null, components.tbl_user);
            });
        },

        initProjectsNotInThisGroup: function (callback) {
            data.projectDS = [];
            components.input_psearch.select2({
                data: function () {
                    return {results: data.projectDS};
                },
                tags: true
            });
        },

        reloadProjectsNotInThisGroup: function () {
            data.projectDS = [];
            var gm = {
                id: components.input_id.val()
            };
            components.input_psearch.select2('val', '').trigger("change");

            if (stringUtils.isBlank(gm.id)) {
                return;
            }

            groupM.searchProjectsNotInThisGroup(gm, function (d) {
                var projects = new Array();
                $.each(d, function (i, data) {
                    projects.push({"id": data.id, "text": data.code});
                });
                data.projectDS = projects;
            });
        },

        initUsersNotInThisGroup: function (callback) {
            data.userDS = [];
            components.input_usearch.select2({
                data: function () {
                    return {results: data.userDS};
                },
                tags: true
            });
        },

        reloadUsersNotInThisGroup: function () {
            data.userDS = [];
            var gm = {
                id: components.input_id.val()
            };
            components.input_usearch.select2('val', '').trigger("change");

            if (stringUtils.isBlank(gm.id)) {
                return;
            }

            groupM.searchUsersNotInThisGroup(gm, function (d) {
                var users = new Array();
                $.each(d, function (i, data) {
                    users.push({"id": data.id, "text": data.loginName});
                });
                data.userDS = users;
            });
        },

        initAddClickEvent: function () {
            components.btn_passign.click(function () {
                components.input_pfilter.val('');
                data.searchProject = {"search_EQ_groupId": components.input_id.val()};
                that.assignForGroups("group/assignProjects", components.tbl_project);
            });

            components.btn_uassign.click(function () {
                components.input_ufilter.val('');
                data.searchUser = {"search_EQ_groupId": components.input_id.val()};
                that.assignForGroups("group/assignUsers", components.tbl_user);
            });
        },

        initFilterClickEvent: function () {
            components.btn_pfilter.click(function () {
                data.searchProject = {
                    "search_LIKE_name": components.input_pfilter.val().trim(),
                    "search_EQ_groupId": components.input_id.val()
                };

                that.filterUpdateTable(components.tbl_project);
            });

            components.btn_ufilter.click(function () {
                data.searchUser = {
                    "search_LIKE_name": components.input_ufilter.val().trim(),
                    "search_EQ_groupId": components.input_id.val()
                };
                that.filterUpdateTable(components.tbl_user);
            });
        },

        filterUpdateTable: function (table) {

            if (table == components.tbl_project) {
                table.DataTable().ajax.url("group/findProjectsForGroupByName").load(function () {
                    that.reloadProjectsNotInThisGroup();
                });

                components.input_psearch.select2('val', '');
            }

            if (table == components.tbl_user) {
                table.DataTable().ajax.url("group/findUsersForGroupByName").load(function () {
                    that.reloadUsersNotInThisGroup();
                });
                components.input_usearch.select2('val', '');
            }
        },

        updateTable: function (table) {
            if (table == components.tbl_project) {
                that.reloadProjectsNotInThisGroup();
                components.input_psearch.select2('val', '');
            }

            if (table == components.tbl_user) {
                that.reloadUsersNotInThisGroup();
                components.input_usearch.select2('val', '');
            }

            var currentPage = table.DataTable().page();
            var count = table.DataTable().data().count();
            if (count == 1) {
                if (currentPage == 1) {
                    table.DataTable().ajax.reload(null, true);
                    return;
                }
                else if (currentPage > 1) {
                    table.DataTable().page(currentPage - 1);
                }
            }
            table.DataTable().ajax.reload(null, false);
        },

        assignForGroups: function (url, table) {
            $.ajax({
                "type": "post",
                "url": url,
                "dataType": "json",
                "data": {
                    groupId: components.input_id.val(),
                    userIds: components.input_usearch.select2('val').toString(),
                    projectIds: components.input_psearch.select2('val').toString()
                },
                "success": function (e) {
                    if (e.code == 0) {
                        msgBox.errorBox('DELETE_FAIL');
                        return false;
                    }
                    msgBox.successBox();
                    that.filterUpdateTable(table);
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },

        deleteForGroups: function (url, userId, projectId, table) {
            var arrUser = new Array();
            var arrProject = new Array();
            if (userId != null) {
                arrUser.push(userId);
            }

            if (projectId != null) {
                arrProject.push(projectId);
            }

            $.ajax({
                "type": "post",
                "url": url,
                "dataType": "json",
                "data": {
                    groupId: components.input_id.val(),
                    userIds: arrUser.toString(),
                    projectIds: arrProject.toString()
                },
                "success": function (e) {
                    if (e.code == 0) {
                        msgBox.errorBox('DELETE_FAIL');
                        return false;
                    }
                    msgBox.successBox();
                    that.updateTable(table);
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        }
    }
});
